/**
 * Created by LXhan on 2017/11/15.
 */
var $;
var form;
var buildingId;
var type;
var codeBuilding = "";//商圈楼宇
var codeHtype = '电';//水/电
var codeStype = '总';//总/分
var codePtype = "00";//项目类型
var codePtypeId = '';//项目类型ID
var codeProject = "";//项目名称
var codeProjectId = '';//项目名称ID
var codeLast = "";//编号后四位
var pid = '';
var hydroType = '';
layui.use(['jquery', 'form', 'layer', 'tree'], function () {
    $ = layui.jquery;
    form = layui.form;
    var layer = layui.layer;
    var t = QueryUtils.GetQueryString("t");
    var s = QueryUtils.GetQueryString("s");
    var y = QueryUtils.GetQueryString("y");
    var id = QueryUtils.GetQueryString("id");//水电表ID
    pid = QueryUtils.GetQueryString("pid");//父级ID
    var pCode = QueryUtils.GetQueryString("pCode");//父级编号
    buildingId = QueryUtils.GetQueryString("buildingId");//楼宇ID
    // if(s == 0){
    //     $(".panel-parent").hide();
    // }else {
    //     $(".panel-parent").find("div").find("input").val(pCode);
    //     $(".panel-parent").show();
    // }
    $(".panel-parent").find("div").find("input").val(pCode);
    console.log("t:"+t);
    if(t == 0){
        $(".panel-code").find("label").html("电表编号：");
        $(".panel-type").find("label").html("电表类型：");
        $(".panel-parent").find("label").html("父级电表：");
        $(".panel-parent").find("div").find("input").attr("placeholder","请选择父级电表");
        $(".panel-rates").show();
        codeHtype = '电';
        hydroType = 'b938139a48ed4344a11a7180b48eede6';
        // console.log(111111);
    }else {
        $(".panel-code").find("label").html("水表编号：");
        $(".panel-type").find("label").html("水表类型：");
        $(".panel-parent").find("label").html("父级水表：");
        $(".panel-parent").find("div").find("input").attr("placeholder","请选择父级水表");
        $(".panel-rates").hide();
        codeHtype = '水';
        hydroType = 'ae5806f8184546208411b99e6117eaa2';
        console.log(222222);
    }
    codeBuilding = parent.getCodeBusiness()+'('+parent.getCodeBuild()+')';
    // getTree();
    if(y == 1){
        getHydroInfo(id);
        form.render("checkbox");
    }
    getType(buildingId);
    getFix();
    form.on('submit(electricity)',function (data) {
        data.field.id = id;
        data.field.pid = pid;
        data.field.t = t;
        data.field.s = s;
        data.field.buildingId = buildingId;
        data.field.codeStype = codeStype;
        data.field.codePtype = codePtype;
        data.field.codePtypeId = codePtypeId;
        data.field.codeProject = codeProject;
        data.field.codeProjectId = codeProjectId;
        data.field.codeLast = codeLast;
        var tips;
        var url;
        if(y == 0){
            if(s == 0){
                if(t == 0){
                    tips = "确定保存电表吗";
                }else {
                    tips = "确定保存水表吗";
                }
            }else {
                tips = "确定保存子表吗";
            }
            url = "/hydropower/save";
        }else{
            if(t == 0){
                tips = "确定修改电表吗";
            }else {
                tips = "确定修改水表吗";
            }
            url = "/hydropower/edit";
        }
        layer.msg(tips, {
            time: 0
            , btn: ['确定', '取消']
            , shade: 0.3
            , yes: function (index) {
                layer.close(index);
                $.ajax({
                    url: url,
                    data: data.field,
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (res) {
                        if (res.errcode === "00") {
                            var i = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(i);
                            if(t == 0){
                                parent.initEleTable();
                            }else {
                                parent.initWatTable();
                            }
                            // if(y == 1){
                            //     parent.getPowerInfo(t,id);
                            // }
                            parent.layer.msg("保存成功", {offset: '150px'});
                        } else if (res.errcode === "01") {
                            layer.msg(res.errmsg, function () {
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(XMLHttpRequest.status);
                        console.error(XMLHttpRequest.readyState);
                        console.error(textStatus);
                    }
                });
            }
        });
        return false;
    })

    form.on('select(type)',function (data) {
        var text = data.elem[data.elem.selectedIndex].text;
        var value = data.value;
        codePtype = subStr(text);
        codePtypeId = value;
        getFix();
        getProject(value,buildingId);
    })
    form.on('select(project)',function (data) {
        codeProject = data.elem[data.elem.selectedIndex].text;
        codeProjectId = data.value;
        getFix();
    })
    form.on('radio(radio)', function(data){
        codeStype = data.value;
        getFix();
    });

    //tree背景色修改
    $("body").on("mousedown",".layui-tree a cite",function(){
        $(".layui-tree a cite").css('color','black')
        $(this).css('color','red');
    })
})


function getBuilding() {
    $.ajax({
        type: "post",
        url: "/hydropower/getbuildings",
        async: true,
        data: {
        },
        success: function(rs) {
            if(rs.errcode == "00"){
                $("#buildingE").append($("<option value=''>请选择楼宇</option>"));
                if(rs.data.length>0){
                    $.each(rs.data,function (i,bs) {
                        $("#buildingE").append($("<optgroup label='"+bs.BUSINESS_NAME+"'></optgroup>"));
                        var buildings = bs.childs;
                        if(buildings.length>0){
                            $.each(buildings,function (j,bd) {
                                if(buildingId != null){
                                    if(buildingId ==bd.BUILDING_ID){
                                        $("#buildingE").append($("<option value='"+bd.BUILDING_ID+"' selected>"+bd.BUILDING_NAME+"</option>"));
                                    }else {
                                        $("#buildingE").append($("<option value='"+bd.BUILDING_ID+"'>"+bd.BUILDING_NAME+"</option>"));
                                    }
                                }else {
                                    $("#buildingE").append($("<option value='"+bd.BUILDING_ID+"'>"+bd.BUILDING_NAME+"</option>"));
                                }
                            })
                        }
                    })
                }
                form.render("select");
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {}
    });
}

function getHydroInfo(id) {
    var pid = '';
    $.ajax({
        type: "post",
        url: "/hydropower/findbyidforedit",
        async: false,
        data: {
            id:id
        },
        success: function(rs) {
            if(rs.errcode == "00"){
                var data = rs.data;
                pid = data.PID;
                $(".panel-code-suffix").find("div").find("input").val(data.CODE_LAST);
                $(".panel-code").find("div").find("input").val(data.CODE);
                $("input[name='isCard'][value='"+data.IS_CARD+"']").attr("checked",true);
                $(".panel-rates").find("div").find("input").val(data.RATES);
                $(".panel-remarks").find("div").find("input").val(data.REMARKS);
                if(data.PCODE != null && data.PCODE != ""){
                    $(".panel-parent").find("div").find("input").val(data.PCODE);
                    // $(".panel-parent").show();
                }
                $("input[name='codeStype'][value='"+data.CODE_STYPE+"']").attr("checked",true);
                codeStype = data.CODE_STYPE;
                codePtype = data.CODE_PTYPE;
                codeProject = data.CODE_PROJECT;
                codeLast = data.CODE_LAST;
                codePtypeId = data.CODE_PTYPEID;
                codeProjectId = data.CODE_PROJECTID;
                $("#pname").val(data.PCODE);
                if(data.PCODE != null && data.PCODE.length > 0){
                    setIconDeleteShow(true);
                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {}
    });
    return pid;
}

function getFix() {
//        $(".panel-code-prefix").find("div").find("input").val(codeBuilding+codeHtype+codeStype+codePtype+codeProject);
    $(".panel-code").find("div").find("input").val(codeBuilding+codeHtype+codeStype+codePtype+codeProject+codeLast);
}

function getType(id) {
    $.ajax({
        type: "post",
        url: "/hydropower/findtype",
        async: false,
        data: {
            BUILDING_ID: id
        },
        success: function (rs) {
            if (rs.errcode == "00") {
                $("#type").empty();
                $("#type").append($("<option value='0'>请选择项目类型</option>"));
                $.each(rs.data, function (i, info) {
                    $("#type").append($("<option value='" + info.id + "'>" + info.name + "</option>"));
                })
                if(codePtypeId != ''){
                    $("#type").val(codePtypeId);
                    getProject(codePtypeId,buildingId);
                }
                form.render();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}
function getProject(value,buildingId) {
    $.ajax({
        type: "post",
        url: "/hydropower/findproject",
        async: false,
        data: {
            value:value,
            buildingId:buildingId
        },
        success: function(rs) {
            if(rs.errcode == "00"){
                $("#project").empty();
                $("#project").append($("<option value='0'>请选择项目名称</option>"));
                $.each(rs.data,function (i,info) {
                    $("#project").append($("<option value='"+info.id+"'>"+info.name+"</option>"));
                })
                if(codeProjectId != ''){
                    $("#project").val(codeProjectId);
                }
                form.render();
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {}
    });
}

function subStr(val) {
    var str;
    if(val.indexOf("层")>0){
        str = val.substring(0,val.length-1);
        if(str.length<2){
            str="0"+str;
        }
    }else{
        str = "00";
    }
    type = str;
    return str;
}


function getSuffix(self) {
    codeLast = $(self).val();
    getFix();
}

function getTree() {
    $("#hydropower").empty();
    layui.tree({
        elem: '#hydropower' //传入元素选择器
        , nodes: getTreeNodes(hydroType, buildingId)
        , click: function (node) {
            pid = node.id;
            $("#pname").val(node.name);
            setIconDeleteShow(true);
        }
    });
}

function getTreeNodes(type, buildingId) {
    var nodes;
    $.ajax({
        type: "post",
        url: "/hydropower/findbypid",
        async: false,
        data: {
            buildingId: buildingId,
            type: type
        },
        success: function (rs) {
            nodes = rs.data;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
    return nodes;
}
function setIconDeleteShow(state) {
    if(state){
        $(".icon-delete").css("display","inline-block");
    }else {
        $(".icon-delete").css("display","none");
    }
}
function clearParentInfo() {
    pid = '';
    $("#pname").val('');
    setIconDeleteShow(false);
}

function initTree() {
    layer.open({
        type: 2,
        title: "父表",
        shadeClose: false,
        shade: [0.3],
        maxmin: false, //开启最大化最小化按钮
        area: ['600px', '400px'],
        scrollbar: false, //屏蔽滚动条
        content: 'water_tree.html?buildingId=' + buildingId + '&hydroType=' + hydroType
    });
}
//父级电表赋值
function initParent(id,value) {
    pid = id;
    $("#pname").val(value);
    setIconDeleteShow(true);
    $("input[name='codeStype'][value='分']").attr("checked",true);
    $("input[name='codeStype'][value='总']").attr("checked",false);
    form.render("radio");
}